package com.yonyou.cyxdms.sysAuth.service.service.role;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoleilu.hutool.util.ObjectUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.exception.DALException;
import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyx.function.utils.common.CommonUtils;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyx.function.utils.jsonserializer.JSONUtil;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.framework.service.cache.DictCacheServiceImpl;
import com.yonyou.cyxdms.sysAuth.service.constants.CommonConstants;
import com.yonyou.cyxdms.sysAuth.service.constants.ManageDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.dto.CodeDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.CommonTreeDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.CommonTreeStateDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.role.RolePDto;
import com.yonyou.cyxdms.sysAuth.service.entity.*;
import com.yonyou.cyxdms.sysAuth.service.entity.role.RolePO;
import com.yonyou.cyxdms.sysAuth.service.entity.role.RolePositionPO;
import com.yonyou.cyxdms.sysAuth.service.mapper.*;
import com.yonyou.cyxdms.sysAuth.service.service.manage.employee.EmployeeService;
import com.yonyou.cyxdms.sysAuth.service.vo.role.PermissionMenuRangeVO;
import com.yonyou.cyxdms.sysAuth.service.vo.role.PermissionMenuVO;
import com.yonyou.cyxdms.sysAuth.service.vo.role.RolePageVO;
import com.yonyou.cyxdms.sysAuth.service.vo.role.RoleVO;
import com.yonyou.cyxdms.sysmanage.client.vo.role.UserbyRoleVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 角色信息实现类
 *
 * @author yll
 * @date 2017年5月27日
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class RoleServiceImpl implements RoleService {

    // 定义日志接口
    private static final Logger logger = LoggerFactory.getLogger(RoleServiceImpl.class);

    @Autowired
    RoleMapper roleMapper;
    @Autowired
    MenuMapper menuMapper;
    @Autowired
    PermissionMenuMapper permissionMenuMapper;
    @Autowired
    CodeMapper codeMapper;
    @Autowired
    PermissionCtrlMapper permissionCtrlMapper;
    @Autowired
    MenuActionMapper menuActionMapper;
    @Autowired
    PermissionMenuActionMapper permissionMenuActionMapper;
    @Autowired
    MenuRangeMapper menuRangeMapper;
    @Autowired
    PermissionMenuRangeMapper permissionMenuRangeMapper;
    @Autowired
    OrgPositionRoleMapper orgPositionRoleMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    DictCacheServiceImpl dictCacheService;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private RolePositionMapper rolePositionMapper;
    @Autowired
    private RoleMenuActionService roleMenuActionService;
    @Autowired
    private RoleMenuRangeService roleMenuRangeService;

    /**
     * 添加角色信息
     *
     * @author adu
     * @since 2019/9/19
     */
    @Override
    public Map<String, Object> addRole(RolePDto roleDto) {
        String roleCode = roleDto.getRoleCode();
        //String roleName = roleDto.getRoleName();
        checkCodeAndName(roleDto);  //判断roleCode和roleName是否为空
        if (searchBrandCode(roleCode)) {
            return insertrolepo(roleDto);
        } else {
            throw new ServiceBizException("角色代码不能重复");
        }
    }

    /**
     * 判断是否存在已有的角色代码和名称
     *
     * @author adu
     * @since 2019/9/19
     */
    private boolean searchBrandCode(String roleCode) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        LambdaQueryWrapper<RolePO> queryWrapper = new QueryWrapper<RolePO>().lambda();
        queryWrapper.eq(RolePO::getRoleCode, roleCode).eq(RolePO::getAppId, loginInfoDto.getAppId());
        //queryWrapper.eq(RolePO::getRoleName, roleName);
        List<RolePO> rolepos = roleMapper.selectList(queryWrapper);
        boolean flag = CommonUtils.isNullOrEmpty(rolepos);
        logger.info("判断是否存在:{}" + flag);
        return flag;
    }

    /**
     * 删除角色及对应权限
     *
     * @author adu
     * @since 2019/9/19
     */
    @Override
    public Integer deleteRoleById(Long permissionId) {
        //删除需判断此角色是否有员工正在使用中，如果有，不能删除
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        List<Map<String, Object>> maps = roleMapper.queryRoleId(permissionId, loginInfoDto.getAppId());
        maps.removeAll(Collections.singleton(null));
        if (maps != null && !maps.isEmpty()) { //有员工正在使用
            throw new DALException("此角色已被使用，不能删除!");
        } else {
            Integer permissionType = ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE;
            //删职位与角色关系表
            LambdaQueryWrapper<OrgPositionRolePO> queryWrapper = new QueryWrapper<OrgPositionRolePO>().lambda();
            queryWrapper.eq(OrgPositionRolePO::getRoleId, permissionId);
            orgPositionRoleMapper.delete(queryWrapper);
            ///删菜单权限，菜单操作权限，菜单数据权限
            roleMapper.deleteA(permissionId);
            roleMapper.deleteR(permissionId);
            roleMapper.deleteC(permissionId, permissionType);
            permissionMenuMapper.deletePermissionMenu(permissionId, permissionType);
            roleMapper.deleteRolePosition(permissionId);
            ///删受控权限
            return roleMapper.deleteRoleById(permissionId);
        }

    }

    @Override
    public Integer updateRoleNameById(String roleName, String id) {
        return roleMapper.updateRoleNameById(roleName, Integer.valueOf(id));
    }

    @Override
    public Integer updateRoleNameByIds(String roleName, Integer isValid, String id) {
        return roleMapper.updateRoleNameByIds(roleName, isValid, Integer.valueOf(id));
    }

    /**
     * 分页条件查询角色
     *
     * @author adu
     * @since 2019/9/19
     */
    @Override
    public IPage<RolePageVO> queryRole(Page<RolePageVO> page, Map<String, Object> queryCondition) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Long companyId = loginInfoDto.getCompanyId();
        Integer companyType = companyMapper.queryComTypeById(companyId);

        Integer factoryId = companyMapper.queryFactoryIdByAppId(loginInfoDto.getAppId());
        List<RolePageVO> voList = roleMapper.pageRole(page, queryCondition, companyType, factoryId);

        List<CodeDTO> list1006 = employeeService.findTcCodeByType(Long.valueOf(1006));
        List<CodeDTO> list1007 = employeeService.findTcCodeByType(Long.valueOf(1007));
        List<CodeDTO> list1099 = employeeService.findTcCodeByType(Long.valueOf(1099));

        for (RolePageVO vo : voList) {
            String posiCode = vo.getPositionCode();
            List<String> posiCodeContent = new ArrayList<>();
            if (null != posiCode) {
                List<String> codes = Arrays.asList(posiCode.split(","));
                for (String cd : codes) {
                    if (cd.startsWith("1006")) {
                        for (CodeDTO codeDTO : list1006) {
                            if (Integer.valueOf(cd).equals(codeDTO.getCodeId())) {
                                posiCodeContent.add(codeDTO.getCodeCnDesc());
                                break;
                            }
                        }
                    } else if (cd.startsWith("1007")) {
                        for (CodeDTO codeDTO : list1007) {
                            if (Integer.valueOf(cd).equals(codeDTO.getCodeId())) {
                                posiCodeContent.add(codeDTO.getCodeCnDesc());
                                break;
                            }
                        }
                    } else if (cd.startsWith("1099")) {
                        for (CodeDTO codeDTO : list1099) {
                            if (Integer.valueOf(cd).equals(codeDTO.getCodeId())) {
                                posiCodeContent.add(codeDTO.getCodeCnDesc());
                                break;
                            }
                        }
                    }
                }
            }
//            vo.setPositionCode(org.apache.commons.lang.StringUtils.join(posiCodeContent.toArray(), ","));
            vo.setCodeCnDesc(org.apache.commons.lang.StringUtils.join(posiCodeContent.toArray(), ","));
            if (vo.getCompanyId() == -1) {
                vo.setCompile(10041002);
            } else if (ManageDictCodeConstants.ORG_TYPE_DEALER_COMPANY == companyType) {
                if (vo.getDataSource().equals(10451002)) {
                    vo.setCompile(10041002);
                } else {
                    vo.setCompile(10041001);
                }
            } else {
                vo.setCompile(10041001);
            }
        }
        page.setRecords(voList);
        return page;
    }

    /**
     * 是否可分配
     *
     * @author adu
     * @since 2019/8/26
     */
    @Override
    public Integer isFixed() {
        Map<String, Object> map = roleMapper.selectIsFixed();
        Integer isFixed = 0;
        if (!CommonUtils.isNullOrEmpty(map) && !StringUtils.isNullOrEmpty(map.get("IS_FIXED"))) {
            isFixed = (Integer) map.get("IS_FIXED");
        }
        return isFixed;
    }

    @Override
    public List<Map<String, String>> queryByRoleId(Integer roleId) {
        return roleMapper.queryByRoleIds(roleId);
    }

    /**
     * 加载菜单
     *
     * @author dengqiang
     * @since 2019/7/10
     */
    @Override
    public List<CommonTreeDTO> querygfkmenu(String roleId) throws ServiceBizException {
        //RolePO role=RolePO.findById(roleId);
        //获取登陆信息
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Integer isFixed = userMapper.getDealerIsFixed(loginInfoDto.getCompanyId());
        Integer orgType = loginInfoDto.getDataType().intValue();

        RolePO rolePO = roleMapper.selectById(roleId);
        Integer dataSource = rolePO.getDataSource();
        Integer dataType = rolePO.getDataType();

        //不固化的
        List<String> list = new ArrayList<>();
        if (roleId != null) {
            String[] ids = roleId.split(",");
            for (String splId : ids) {
                list.add(splId);
            }
        }
        List<Map<String, Object>> listmap = roleMapper.findAllCommonTree(orgType, loginInfoDto.getAppId(), list, ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE, dataSource, dataType);

        List<CommonTreeDTO> orgList = new ArrayList<>();
        Iterator<Map<String, Object>> it = listmap.iterator();
        while (it.hasNext()) {
            CommonTreeStateDTO commonTreeStateDto = new CommonTreeStateDTO();
            CommonTreeDTO orgTreeOrg = new CommonTreeDTO();
            Map<String, Object> menuMap = it.next();
            orgTreeOrg.setId(menuMap.get("MENU_ID").toString());
            String parent = menuMap.get("PARENT_ID").toString();
            if ("0".equals(parent)) {
                parent = "#";
            }
            Object menuId = menuMap.get("MENU_ID");
            if (!ObjectUtils.isEmpty(menuId)) {
                commonTreeStateDto.setChecked(!StringUtils.isNullOrEmpty(menuMap.get("PERMISSION_MENU_ID")) && StringUtils.isEquals(ManageDictCodeConstants.STATUS_IS_YES, menuMap.get("IS_EMPOWERED").toString()) && (Long) menuId > 99999);

                if (!StringUtils.isNullOrEmpty(menuMap.get(CommonConstants.IS_FLEXIBLE)) && !StringUtils.isEquals(ManageDictCodeConstants.STATUS_IS_YES, menuMap.get(CommonConstants.IS_FLEXIBLE).toString()) && StringUtils.isEquals(ManageDictCodeConstants.STATUS_IS_YES, isFixed.toString())) {
                    commonTreeStateDto.setCheckboxDisabled(true);
                }
                if (!StringUtils.isNullOrEmpty(menuMap.get(CommonConstants.IS_FLEXIBLE)) && StringUtils.isEquals(ManageDictCodeConstants.STATUS_IS_YES, menuMap.get(CommonConstants.IS_FLEXIBLE).toString()) && StringUtils.isEquals(ManageDictCodeConstants.STATUS_IS_YES, isFixed.toString())) {
                    menuMap.put(CommonConstants.MENU_NAME, menuMap.get(CommonConstants.MENU_NAME).toString() + "[可分配]");
                }
                //2019-8-9修改增加 柔性权限修改，通过经销商的参数配置，来设置柔性权限的修改
                if (!StringUtils.isNullOrEmpty(menuMap.get("IS_FLEXIBLE")) && StringUtils.isEquals(ManageDictCodeConstants.STATUS_IS_YES, menuMap.get("IS_FLEXIBLE").toString()) && StringUtils.isEquals(ManageDictCodeConstants.STATUS_IS_YES, isFixed.toString())) {
                    commonTreeStateDto.setDisabled(true);
                }
                orgTreeOrg.setParent(parent);
                orgTreeOrg.setText(menuMap.get(CommonConstants.MENU_NAME).toString());
                orgTreeOrg.setState(commonTreeStateDto);
                orgList.add(orgTreeOrg);
            }

        }
        return orgList;

    }

    /**
     * 权限置空
     *
     * @author dengqiang
     * @since 2019/7/12
     */
    @Override
    public void emptyRoleById(Long id) {
        //菜单权限置空
        List<Map<String, Object>> list = roleMapper.selectPermissionMenuId(id, ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE);

        for (int i = 0; i < list.size(); i++) {
            Object menuid = list.get(i).get("PERMISSION_MENU_ID");
            Integer permissionMenuId = Integer.parseInt(menuid.toString());
            permissionMenuActionMapper.updatePermissionMenuAction(ManageDictCodeConstants.STATUS_IS_NOT, permissionMenuId);
            permissionMenuRangeMapper.updatePermissionMenuRange(ManageDictCodeConstants.STATUS_IS_NOT, permissionMenuId);
        }

        permissionMenuMapper.updatePermissionMenu(ManageDictCodeConstants.STATUS_IS_NOT, id, ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE);
        //受控权限置空
        List<Map<String, Object>> list2 = roleMapper.selectPermissionCtrlId(id, ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE);
        for (int i = 0; i < list2.size(); i++) {
            Object ctrlId = list2.get(i).get("PERMISSION_CTRL_ID");
            PermissionCtrlPO permissionctrlpo = permissionCtrlMapper.selectById(Integer.parseInt(ctrlId.toString()));
            permissionctrlpo.setIsEmpowered(ManageDictCodeConstants.STATUS_IS_NOT);
            permissionCtrlMapper.updateById(permissionctrlpo);
        }

    }

    /**
     * 修改一条权限菜单
     *
     * @author dengqiang
     * @since 2019/7/12
     */
    @Override
    public void editPermissionMenu(Integer permissionType, String permissionId, Long menuid) {
        if (StringUtils.isNullOrEmpty(permissionId)) {
            throw new ServiceBizException("权限id不能为空");
        }
        if (StringUtils.isNullOrEmpty(permissionType)) {
            throw new ServiceBizException("权限类型不能为空");
        }
        if (StringUtils.isNullOrEmpty(menuid)) {
            throw new ServiceBizException("菜单id不能为空");
        }

        List<Map<String, Object>> list = roleMapper.selctMenuId(menuid);

        if (CommonUtils.isNullOrEmpty(list)) {
            roleMapper.updatePermissionMenu(permissionType, Integer.parseInt(permissionId), menuid, ManageDictCodeConstants.STATUS_IS_YES);
        }

    }

    /**
     * 角色新增页面初始化数据
     *
     * @author dengqiang
     * @since 2019/7/24
     */
    @Override
    public List<Map<String, Object>> queryMenu(Integer dataType) {
        List<Map<String, Object>> list;
        if (ManageDictCodeConstants.DATA_TYPE_BY_GROUP == dataType) {
            list = roleMapper.queryMenuOne();
        } else {
            list = roleMapper.queryMenuTwo();
        }

        return list;
    }

    public void checkCodeAndName(RolePDto roleDto) {
        if (StringUtils.isNullOrEmpty(roleDto.getRoleCode())) {
            throw new ServiceBizException("角色代码");
        }
        if (StringUtils.isNullOrEmpty(roleDto.getRoleName())) {
            throw new ServiceBizException("角色名称");
        }
    }

    public void setrolepo(RolePO rolepo, RolePDto roleDto) {
        rolepo.setRoleCode(roleDto.getRoleCode());
        rolepo.setRoleName(roleDto.getRoleName());
        rolepo.setRoleType(roleDto.getRoleType());
        if (!StringUtils.isNullOrEmpty(roleDto.getDataSource())) {
            rolepo.setDataSource(roleDto.getDataSource());
        }
        if (!StringUtils.isNullOrEmpty(roleDto.getDataType())) {
            rolepo.setDataType(roleDto.getDataType());
        }
    }

    /**
     * 新增角色
     *
     * @param roleDto
     * @return java.lang.Integer
     * @author adu
     * @since 2019/9/19
     */
    public Map<String, Object> insertrolepo(RolePDto roleDto) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        RolePO rolepo = new RolePO();
        rolepo.setCompanyId(loginInfoDto.getCompanyId().intValue());
        rolepo.setAppId(loginInfoDto.getAppId());

        setrolepo(rolepo, roleDto);
        if (roleDto.getDataType().equals(ManageDictCodeConstants.DATA_TYPE_BY_OWNER)) {
            rolepo.setDataType(ManageDictCodeConstants.DATA_TYPE_BY_OWNER);
            rolepo.setDataSource(ManageDictCodeConstants.DATA_SOURCES_BY_OWNER);
        } else {
            rolepo.setDataType(ManageDictCodeConstants.DATA_TYPE_BY_SUPER);
            rolepo.setDataSource(ManageDictCodeConstants.DATA_SOURCES_BY_SUPER);
        }
        Integer isValid = roleDto.getIsValid();
        if (null == isValid) {
            roleMapper.insert(rolepo);
        } else {
            rolepo.setIsValid(roleDto.getIsValid());//是否关键岗位
            rolepo.setDataType(ManageDictCodeConstants.DATA_TYPE_BY_OWNER);
            roleMapper.insert(rolepo);
        }

        Integer roleId = rolepo.getRoleId().intValue();
        //新增角色的时候把对应的权限都赋值给他，是否柔性和是否有权限都默认为否
        //角色菜单
        LambdaQueryWrapper<MenuPO> queryWrapper = new QueryWrapper<MenuPO>().lambda();
        queryWrapper.eq(MenuPO::getMenuStatus, ManageDictCodeConstants.STATUS_IS_VALID);
        queryWrapper.eq(MenuPO::getDataType, loginInfoDto.getDataType());
        queryWrapper.eq(MenuPO::getAppId, loginInfoDto.getAppId());
        List<MenuPO> menupos = menuMapper.selectList(queryWrapper);

        Integer orgType = ManageDictCodeConstants.DATA_TYPE_BY_OWNER;
        PermissionMenuPO permissionmenupo1 = null;

        for (MenuPO menupo : menupos) {
            permissionmenupo1 = new PermissionMenuPO();
            permissionmenupo1.setAppId(loginInfoDto.getAppId());
            permissionmenupo1.setPermissionType(ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE);
            permissionmenupo1.setPermissionId(roleId);
            permissionmenupo1.setMenuId(menupo.getMenuId());
            permissionmenupo1.setIsFlexible(ManageDictCodeConstants.STATUS_IS_YES);
            permissionmenupo1.setIsEmpowered(ManageDictCodeConstants.STATUS_IS_NOT);
            logger.debug("===================================>>>>>>>>>>>>>>>> permissionMenuMapper.insert(permissionMenuPO);");
            permissionMenuMapper.insert(permissionmenupo1);
        }
        String appId = loginInfoDto.getAppId();

        List<PermissionMenuVO> permissionmenuvos = menuActionMapper.selectPermissionMenuAction(orgType, loginInfoDto.getAppId());

        PermissionMenuActionPO permissionmenuactionpo = null;
        for (PermissionMenuVO permissionMenuVO : permissionmenuvos) {
            Long menuId = permissionMenuVO.getMenuId();
            List<Long> permissionMenuIds = permissionMenuMapper.selectIdByMenuIdAndRoleId(menuId, appId, roleId);
            if (permissionMenuIds.size() == 1) {
                permissionmenuactionpo = new PermissionMenuActionPO();
                permissionmenuactionpo.setPermissionMenuId(permissionMenuIds.get(0));
                permissionmenuactionpo.setMenuCuringId(permissionMenuVO.getMenuCuringId());
                permissionmenuactionpo.setIsFlexible(ManageDictCodeConstants.STATUS_IS_YES);
                permissionmenuactionpo.setIsEmpowered(ManageDictCodeConstants.STATUS_IS_NOT);
                permissionMenuActionMapper.insert(permissionmenuactionpo);
            }
        }
        List<PermissionMenuRangeVO> permissionmenurangevos = menuRangeMapper.selectPermissionMenuRange(orgType, loginInfoDto.getAppId());
        PermissionMenuRangePO permissionmenurangepo = null;

        for (PermissionMenuRangeVO permissionMenuRangeVO : permissionmenurangevos) {
            Long menuId = permissionMenuRangeVO.getMenuId();
            List<Long> permissionMenuIds = permissionMenuMapper.selectIdByMenuIdAndRoleId(menuId, appId, roleId);
            if (permissionMenuIds.size() == 1) {
                permissionmenurangepo = new PermissionMenuRangePO();
                permissionmenurangepo.setPermissionMenuId(permissionMenuIds.get(0));
                permissionmenurangepo.setMenuRangeId(permissionMenuRangeVO.getMenuRangeId());
                permissionmenurangepo.setIsFlexible(ManageDictCodeConstants.STATUS_IS_YES);
                permissionmenurangepo.setIsEmpowered(ManageDictCodeConstants.STATUS_IS_NOT);
                permissionMenuRangeMapper.insert(permissionmenurangepo);
            }
        }
        //直接返回新增的角色名称
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("roleId", roleId);
        map.put("roleCode", roleDto.getRoleCode());
        map.put("roleName", roleDto.getRoleName());
        map.put("roleType", roleDto.getRoleType());
        map.put("isValid", roleDto.getIsValid());//是否关键岗位
        return map;
    }

    /**
     * 通过角色类别查询用户信息
     *
     * @author maxingjian
     * @since 2019/9/18
     */
    @Override
    public List<UserbyRoleVO> getUserInfoByRolePosition(String positionCode, String companyId, String ownerCode) {
        String[] idsArray = null;
        if (!StringUtils.isNullOrEmpty(companyId)) {
            idsArray = companyId.split(",");
        }
        String[] positionArray = null;
        logger.info("positionCode ==================================================================================================================" +
                "===================================================================================================" + positionCode);
        if (StrUtil.isEmpty(positionCode)) {
            System.out.println("positionCode ==================================================================================================================" +
                    "===========================================================空空空空空空空空空空空空空空空空空空空空空空空空空空空空");
        }
        if (!StringUtils.isNullOrEmpty(positionCode)) {
            positionArray = positionCode.split(",");
        }
        Map<String, Object> params = new HashMap<>();
        params.put("idsArray", idsArray);
        params.put("positionArray", positionArray);
        List<UserbyRoleVO> userInfoByRole = roleMapper.getUserInfoByRole(params, ownerCode, null);
        return userInfoByRole;
    }

    /**
     * 通过角色查询用户信息
     *
     * @author maxingjian
     * @since 2019/9/18
     */
    @Override
    public List<UserbyRoleVO> getUserInfoByRole(String roleCode, String companyId) {
        String[] idsArray = null;
        String[] roleCodes = null;
        if (!StringUtils.isNullOrEmpty(companyId)) {
            idsArray = companyId.split(",");
        }
        if (!StringUtils.isNullOrEmpty(roleCode)) {
            roleCodes = roleCode.split(",");
        }
        if (roleCodes == null || roleCodes.length == 0) {
            return null;
        }
        Map<String, Object> params = new HashMap<>();
        params.put("idsArray", idsArray);
        return roleMapper.getUserInfoByRole(params, null, roleCodes);
    }

    /**
     * 通过角色查询用户信息
     *
     * @author maxingjian
     * @since 2019/9/18
     */
    @Override
    public List<RolePO> getRole(Long companyId) {
        LambdaQueryWrapper<RolePO> queryWrapper = new QueryWrapper().lambda();
        queryWrapper.eq(RolePO::getCompanyId, companyId);
        return roleMapper.selectList(queryWrapper);
    }

    @Override
    public IPage<RolePageVO> getUserRoleName(Page<RolePageVO> page, Map<String, Object> queryCondition) {
        List<RolePageVO> voList = roleMapper.getUserRoleName(page, queryCondition);
        page.setRecords(voList);
        return page;
    }

    /**
     * 获取厂端预置的所有角色
     *
     * @author 李贺
     * @since 2019/11/18
     */
    @Override
    public List<RoleVO> getPresetRole() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Long dataType = loginInfoDto.getDataType();
        Long factoryId = companyMapper.findFactoryIdByAppId(loginInfoDto.getAppId());
        return roleMapper.getPresetRole(factoryId, ManageDictCodeConstants.DATA_SOURCES_BY_SUPER, dataType);
    }

    /**
     * 保持编辑角色权限
     *
     * @author 李贺
     * @since 2019/12/16
     */
    @Override
    @Transactional
    public void modifyOrg(RolePDto rolepdto) {

        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        String appId = loginInfoDto.getAppId();
        Long userId = loginInfoDto.getUserId();

        //找到角色跟新名称
        RolePO rolePo = roleMapper.selectById(rolepdto.getRoleId());
        if (rolePo != null) {
            rolePo.setRoleName(rolepdto.getRoleName());
            rolePo.setRoleType(rolepdto.getRoleType());
            rolePo.setUpdatedAt(LocalDateTime.now());
            roleMapper.updateById(rolePo);
        }

        //职位
        List<String> positionList = rolepdto.getCheckedList1();
        positionList.addAll(rolepdto.getCheckedList2());
        positionList.addAll(rolepdto.getCheckedListAll());

        String nowTree = rolepdto.getNowTree();
        String treeMenuAction = rolepdto.getTreeMenuAction();
        String treeMenuRange = rolepdto.getTreeMenuRange();
        List<String> favorableModels = rolepdto.getFavorableModels();//优惠模式
        List<String> maintain = rolepdto.getMaintain();//维修
        List<String> accessories = rolepdto.getAccessories();//配件
        if (StringUtils.isNullOrEmpty(nowTree)) {//菜单权限不能为空
            throw new ServiceBizException("菜单权限不能为空");
        }
        //删除所有职位
        Long roleId = rolepdto.getRoleId().longValue();
        rolePositionMapper.deleteRolePermission(roleId.intValue());

        if (!CollectionUtils.isEmpty(positionList)) {
            RolePositionPO rolepositionpo = new RolePositionPO();
            rolepositionpo.setRoleId(roleId);
            for (String position : positionList) {
                rolepositionpo.setRolePositionId(null);
                rolepositionpo.setPositionCode(Integer.parseInt(position));
                rolePositionMapper.insert(rolepositionpo);
            }
        }
        RolePO rolepo = roleMapper.selectById(roleId);
        permissionMenuMapper.insertOtherRoleMenu(roleId, appId, loginInfoDto.getUserId(), rolepo.getDataType());

        permissionMenuMapper.updateOldRolePermission(roleId);

        String[] sourceStrArray = nowTree.split(",");
        if (sourceStrArray.length != 0) {
            permissionMenuMapper.updateByMenuIdsAndRoleId(roleId, sourceStrArray);
        }

        //删除menuCtrl内容
        permissionCtrlMapper.deletePermissionCtrlByRoleId(roleId);

        if (!CommonUtils.isNullOrEmpty(maintain)) {
            Integer type = ManageDictCodeConstants.MAINTAIN;
            permissionCtrlMapper.insertRoleCtrl(maintain, type, roleId, appId, userId);
        }
        if (!CommonUtils.isNullOrEmpty(accessories)) {
            Integer type = ManageDictCodeConstants.ACCESSORIES;
            permissionCtrlMapper.insertRoleCtrl(accessories, type, roleId, appId, userId);
        }
        if (!CommonUtils.isNullOrEmpty(favorableModels)) {
            Integer type = ManageDictCodeConstants.FAVORABLE_MODELS;
            permissionCtrlMapper.insertRoleCtrl(favorableModels, type, roleId, appId, userId);
        }

        //treeMenuAction
        permissionMenuActionMapper.deleteActionByRoleId(roleId);
        permissionMenuRangeMapper.deleteRangeByRoleId(roleId);

        if (!StringUtils.isNullOrEmpty(treeMenuAction)) {
            String[] oneAction = treeMenuAction.split(";");
            if (oneAction.length > 0) {
                for (int i = 0; i < oneAction.length; i++) {
                    if (!StringUtils.isNullOrEmpty(oneAction[i])) {
                        roleMenuActionService.editOneAction(oneAction[i], ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE, roleId.toString());
                    }
                }
            }
        }
        //treeMenuRange
        if (!StringUtils.isNullOrEmpty(treeMenuRange)) {
            String[] oneRange = treeMenuRange.split(";");
            if (oneRange.length > 0) {
                for (int i = 0; i < oneRange.length; i++) {
                    if (!StringUtils.isNullOrEmpty(oneRange[i])) {
                        roleMenuRangeService.editOneRange(oneRange[i], ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE, roleId.toString());
                    }
                }
            }
        }

        // 厂端--插入人员菜单
        if (ObjectUtil.isNotNull(rolepdto.getDataSource()) && rolepdto.getDataSource().equals(Integer.valueOf(ManageDictCodeConstants.DATA_SOURCES_BY_SUPER))) {
            // 根据roleId删除所有人员菜单关系
            permissionMenuMapper.deleteByRoleId(rolepdto.getRoleId().longValue());
            permissionMenuMapper.insertUpdateMenuOem(appId, rolepdto.getRoleId().longValue());

            //同步按钮权限
            permissionMenuActionMapper.deleteUserActionByRoleId(roleId);
            permissionMenuActionMapper.insertUserActionByRoleId(roleId);
        }
        else {
            permissionMenuMapper.deleteByRoleId(rolepdto.getRoleId().longValue());
            // 店端--插入人员菜单
            permissionMenuMapper.insertUpdateMenuDlr(appId, rolepdto.getRoleId().longValue());
        }

    }

    @Override
    public List<RoleVO> getPresetRoleByName(List<String> names) {
        logger.info(JSONUtil.objectToJson(names));
        List<RoleVO> roleList= null;
        try {
            roleList = roleMapper.getPresetRoleByName(names);
        }catch (Exception e){
            logger.info(e.getMessage(),e);
            e.printStackTrace();
        }
        return roleList;
    }

}
